package com.cloud.note.service.impl;

import com.cloud.note.dto.tag.CreateTagRequest;
import com.cloud.note.dto.tag.TagResponse;
import com.cloud.note.model.Tag;
import com.cloud.note.repository.TagRepository;
import com.cloud.note.service.TagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

@Service
public class TagServiceImpl implements TagService {

    @Autowired
    private TagRepository tagRepository;

    @Override
    public List<TagResponse> getAllTags(String userId) {
        List<Tag> tags = tagRepository.findByUserId(userId);

        return tags.stream()
                .map(tag -> TagResponse.builder()
                        .id(tag.getId())
                        .name(tag.getName())
                        .color(tag.getColor())
                        .noteCount((long) tag.getNotes().size())
                        .createdAt(tag.getCreatedAt())
                        .build())
                .collect(Collectors.toList());
    }

    @Override
    @Transactional
    public TagResponse createTag(String userId, CreateTagRequest createTagRequest) {
        // 检查标签名称是否已存在
        if (tagRepository.existsByUserIdAndName(userId, createTagRequest.getName().trim())) {
            throw new RuntimeException("标签名称已存在");
        }

        // 创建新标签
        Tag tag = new Tag();
        tag.setId(UUID.randomUUID().toString());
        tag.setUserId(userId);
        tag.setName(createTagRequest.getName().trim());
        tag.setColor(createTagRequest.getColor() != null ? createTagRequest.getColor() : "#2196F3");
        tag.setCreatedAt(LocalDateTime.now());

        tagRepository.save(tag);

        return TagResponse.builder()
                .id(tag.getId())
                .name(tag.getName())
                .color(tag.getColor())
                .noteCount(0L)
                .createdAt(tag.getCreatedAt())
                .build();
    }

    @Override
    @Transactional
    public TagResponse updateTag(String userId, String tagId, CreateTagRequest updateTagRequest) {
        // 获取标签
        Tag tag = tagRepository.findByIdAndUserId(tagId, userId)
                .orElseThrow(() -> new RuntimeException("标签不存在"));

        // 如果要更改名称，检查是否重复
        if (!tag.getName().equals(updateTagRequest.getName().trim())) {
            if (tagRepository.existsByUserIdAndName(userId, updateTagRequest.getName().trim())) {
                throw new RuntimeException("标签名称已存在");
            }
            tag.setName(updateTagRequest.getName().trim());
        }

        // 更新颜色
        if (updateTagRequest.getColor() != null) {
            tag.setColor(updateTagRequest.getColor());
        }

        tagRepository.save(tag);

        return TagResponse.builder()
                .id(tag.getId())
                .name(tag.getName())
                .color(tag.getColor())
                .noteCount((long) tag.getNotes().size())
                .createdAt(tag.getCreatedAt())
                .build();
    }

    @Override
    @Transactional
    public void deleteTag(String userId, String tagId) {
        Tag tag = tagRepository.findByIdAndUserId(tagId, userId)
                .orElseThrow(() -> new RuntimeException("标签不存在"));

        tagRepository.delete(tag);
    }
}